//
//  HomeViewController.m
//  XinKaiFa55like
//
//  Created by junseek on 2017/7/31.
//  Copyright © 2017年 55like lj. All rights reserved.
//
#import "WSButtonGroup.h"
#import "V4HomeViewController.h"
#import "RHTableView.h"
#import "LJImageRollingView.h"
#import "SelectWebUrlViewController.h"
#import "V4TestLicensePlateContentViewController.h"
#import "HomeTableViewCell.h"
#import "JPUSHService.h"
#import "CompanyNoticeViewController.h"
#import "V4LicensePlateViewController.h"
#import "V4AddLicensePlateViewController.h"
#import "UserProjectViewController.h"
#import "V4Home01View.h"
#import "V4Home02View.h"
#import "V4HomeLeftView.h"
#import "V4SearchViewController.h"

@interface V4HomeViewController ()<LJImageRollingViewDelegate,WSButtonGroupdelegate>{
    LJImageRollingView *imageRolling;
    RHTableView *table_user;
    UIScrollView *scrollTypeBG;
    UIView *viewHeaderBG;
    UIPageControl *_pageControl;
    
    UIImageView *imageTipNav;
    
    BOOL boolRefreshData;
    
     UIScrollView*scrollView;
    
    
    
    WSButtonGroup*_topBtnGroup;
    
    V4Home01View*_view1;
    UIView*_topSelectView;

}
@property(nonatomic,strong)V4Home01View*view1;
@property(nonatomic,strong)NSMutableArray*topViewArray;
@end

@implementation V4HomeViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [imageRolling startAnimation];
    if (boolRefreshData) {
        boolRefreshData=NO;
        [self refreshTableViewData];
    }
    if (_view1.hidden==NO) {
        [_view1 request];
    }
    
    
    [self refreshNotice_redData];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [imageRolling stopAnimation];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    RegisterNotify(@"againLoadUserData", @selector(againLoadUserData))
    RegisterNotify(@"JPushMessage", @selector(pushMessageData:))
    RegisterNotify(@"sendAddPZClicked", @selector(sendAddPZClicked))
    
    [self navbarTitle:@" "];
//  [self leftButton:nil image:@"zxmenu" sel:@selector(myleftBtnClick:)];
//    self.navleftButton.userInteractionEnabled=NO;
    
    //隐藏按钮
//    [self rightButton:nil image:@"headersy" sel:@selector(rightButtonClicke)];
    
    imageTipNav=[RHMethods imageviewWithFrame:CGRectMake(kScreenWidth-13, 27, 7, 7) defaultimage:@"redTip070116" contentMode:UIViewContentModeScaleAspectFit];
    [self.navView addSubview:imageTipNav];
    imageTipNav.hidden=YES;
    
    UIButton *btnSearch=[RHMethods buttonWithFrame:CGRectMake(65-20, 29, kScreenWidth-110+20, 26) title:@" 请输入公司名称等关键字" image:@"jianliseach" bgimage:nil];
    
    btnSearch.frame=CGRectMake(15, 29, kScreenWidth-110+20+30+30, 26);
    btnSearch.titleLabel.font=fontSmallTitle;
    [btnSearch setTitleColor:rgbTxtGray forState:UIControlStateNormal];
    [btnSearch setBackgroundColor:[UIColor whiteColor]];
    [[Utility Share] viewLayerRound:btnSearch borderWidth:0.1 cornerRadius:4 borderColor:[UIColor whiteColor]];
    [btnSearch addTarget:self action:@selector(searchButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:btnSearch];
    
//    [self addView];
    //获取广告
    [self welcomeLoginAdvertising];
    
    if ([[[Utility Share] userId] notEmptyOrNull] && [[[Utility Share] userToken] notEmptyOrNull]) {
        [[Utility Share] isLogin:^(NSInteger NoLogin) {
            if (NoLogin != 1) {
                [[Utility Share] showLoginAlert:YES];
            }else{
                
                [[Utility Share] versionUpdate:NO];
                [self againLoadUserData];
            }
        }];
    }else{
        [[Utility Share] showLoginAlert:NO];
    }
    
    
}

-(void)myleftBtnClick:(UIButton*)btn{
      __weak __typeof(self) weakSelf = self;
    [V4HomeLeftView showMeWithCallBackBlock:^(id data, int status, NSString *msg) {
        if (status==200) {
            weakSelf.view1.cid=[data objectForJSONKey:@"id"];
            [weakSelf.view1 request];
        }
    }];
//    self.left
    
    
}
-(void)WSButtonGroupChange:(WSButtonGroup *)btnCrop{
    UIView*viewred=[btnCrop getAddValueForKey:@"viewred"];
    [UIView animateWithDuration:0.2     animations:^{
        viewred.centerX=btnCrop.currentSelectBtn.centerX;
    }];
    for (UIView*view in _topViewArray) {
        view.hidden=YES;
    }
    
    UIView*currentview=_topViewArray[btnCrop.currentindex];
    currentview.hidden=NO;
    if (btnCrop.currentindex==0) {
        self.navleftButton.hidden=NO;
        [_view1 request];
    }else{
        self.navleftButton.hidden=YES;
    }
    
}

-(void)addView{
    if (_topSelectView) {
        [_topSelectView removeFromSuperview];
        _topBtnGroup=nil;
        for (UIView*view in _topViewArray) {
            [view removeFromSuperview];
        }
        [_topViewArray removeAllObjects];
    }
    
    {
    UIView*viewtop=[RHMethods viewWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, 31) backgroundcolor:zrgbwhiteColor superView:self.view];
        _topSelectView=viewtop;
        
//        NSArray*arraytitle=@[@"自选",@"一类",@"二类",@"私募",];
        NSMutableArray*arraytitle=[NSMutableArray new];
        [arraytitle addObject:@"收藏"];
        
        NSArray*bigcateArray=[[UTILITY userTypeData] objectForKey:@"bigcate"];
        for (NSDictionary*bigcate in bigcateArray) {
            [arraytitle addObject:[bigcate objectForJSONKey:@"name"]];
        }
        
        _topBtnGroup=[WSButtonGroup new];
        _topBtnGroup.delegate=self;
        float withbtn=kScreenWidth/arraytitle.count;
        for (int i=0; i<arraytitle.count; i++) {
            NSString*titleStr=arraytitle[i];
             WSSizeButton*btniteme=[RHMethods buttonWithframe:CGRectMake(0+i*withbtn, 0, withbtn, 31) backgroundColor:nil text:titleStr font:14 textColor:rgb(102,102,102) radius:0 superview:viewtop];
            [btniteme setTitleColor:rgb(239,186,57) forState:UIControlStateSelected];
            [_topBtnGroup addButton:btniteme];
        }
        [RHMethods viewWithFrame:CGRectMake(0, 31-0.5, kScreenWidth, 0.5) backgroundcolor:rgb(166,166,166) superView:viewtop];
        UIView*viewred=[RHMethods viewWithFrame:CGRectMake(0, 31-1, 30, 2) backgroundcolor:rgb(239,186,57) superView:viewtop];
        [_topBtnGroup setAddValue:viewred forKey:@"viewred"];
      
        
    }
    
    if (_view1==nil) {
        
        _view1=[[V4Home01View alloc]initWithFrame:CGRectMake(0, kTopHeight+31, kScreenWidth, kScreenHeight-kTopHeight-31-50)];
    }
    _topViewArray=[NSMutableArray new];
    [_topViewArray addObject:_view1];
    [self.view addSubview:_view1];
    
    
    NSArray*bigcateArray=[[UTILITY userTypeData] objectForKey:@"bigcate"];
    for (NSDictionary*bigcate in bigcateArray) {
        
       V4Home02View* view2=[[V4Home02View alloc]initWithFrame:CGRectMake(0, kTopHeight+31, kScreenWidth, kScreenHeight-kTopHeight-31-50)];
        view2.cataDic=bigcate;
        [view2 request];
        [view2 loadHeaderTypeBg];
        [_topViewArray addObject:view2];
        [self.view addSubview:view2];
    }
    
    
      [_topBtnGroup btnClickAtIndex:0];
    //    scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kTopHeight, kScreenWidth, kScreenHeight-kTopHeight)];
//    [self.view addSubview:scrollView];
    
    
}


-(void)welcomeLoginAdvertising{
    //    XKFwelcome
    [NetEngine createGetAction_LJ:XKFwelcome onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            NSMutableArray *arrayA=[NSMutableArray new];
            for (NSDictionary *dc in [[resData objectForJSONKey:@"data"] objectForJSONKey:@"list"]) {
                NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:dc];
                [dic setValue:[dc valueForJSONStrKey:@"2x_path"] forKey:@"url"];
                [arrayA addObject:dic];
            }
            [imageRolling reloadImageView:arrayA selectIndex:0];
        }else{
            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        }
    }];
}
-(void)refreshTableViewData{
//    krequestParam
//    [dictparam setValue:@"20" forKey:@"pagesize"];
//    [dictparam setValue:@"%@" forKey:@"page"];
//    [dictparam setValue:@"index" forKey:@"type"];
//    table_user.urlString=[NSString stringWithFormat:@"%@%@",XKFV4productslists,dictparam.wgetParamStr];
//    [table_user refresh];
}


#pragma mark button
-(void)rightButtonClicke{
    [self pushController:[CompanyNoticeViewController class] withInfo:@"" withTitle:@"重要通知" withOther:@{}];
}
-(void)searchButtonClicked{
    [self pushController:[V4SearchViewController class] withInfo:@"search" withTitle:@"牌照" withOther:nil];
}
#pragma mark selector
-(void)refreshNotice_redData{
    //    XKFV4homesnotice_red
    return;
    krequestParam
    [NetEngine createGetAction_LJ:[NSString stringWithFormat:@"%@%@",XKFV4homesnotice_red,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            imageTipNav.hidden=[[[resData objectForJSONKey:@"data"] valueForJSONStrKey:@"isread"] isEqualToString:@"1"];
            imageTipNav.hidden=YES;
        }else{
            
        }
    }];
}
-(void)againLoadUserData{
    [self loadXKFV4productscate];
    [[Utility Share] setIsUserLogin:YES];
    [[Utility Share] hiddenStartTransitionView];
    
    [[[Utility Share] CustomTabBar_zk] updateCustomTabBarControllers];
    [JPUSHService setAlias:[NSString stringWithFormat:@"%@",[[Utility Share] userId]] callbackSelector:nil object:@""];
    
    
    for (UIView*view in _topViewArray) {
//        if ([view respondsToSelector:@selector(request)]) {
//            [view performSelector:@selector(request) withObject:nil];
//        }
    }
    
//    [self refreshTableViewData];
    
    
    ///处理推送信息
    if ([[Utility Share] isPushMessage] && [[Utility Share] userPushData]) {
        [[Utility Share] setIsPushMessage:NO];
        [self refreshPushUI: [[Utility Share] userPushData]];
    }
}
-(void)pushMessageData:(NSNotification *)note{
    DLog(@"推送信息：%@",[note object]);
    if ([note object]) {
        [self refreshPushUI:[note object]];
    }
}
///获取分类
-(void)loadXKFV4productscate{
    krequestParam
    [NetEngine createGetAction_LJ_two:[NSString stringWithFormat:@"%@%@",XKFV4productscate,dictparam.wgetParamStr] onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            //[resData objectForJSONKey:@"data"]
            [[Utility Share] setUserTypeData:[resData objectForJSONKey:@"data"]];
//            [_view2 loadHeaderTypeBg];
            [self addView];
        }else{
            [self loadXKFV4productscate];
        }
    } onError:^(NSError *error) {
        [self loadXKFV4productscate];
    }];
    
}

-(void)refreshPushUI:(NSDictionary *)dicPush{
    /*
     productpush  牌照推送  demandpush 供求推送  projectpush 项目推送 noticepush公告推送
     */
    if ([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"productpush"]) {//牌照推送
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
            [curNav popToRootViewControllerAnimated:NO];
            [[[Utility Share] CustomTabBar_zk] selectedTabIndex:@"0"];
            [self refreshTableViewData];
        });
        
        //    }else if([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"demandpush"]){//供求推送
        //        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        //        UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
        //        [curNav popToRootViewControllerAnimated:NO];
        //        BaseViewController *baseV=curNav.viewControllers.firstObject;
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            [baseV pushController:[UserSupplyDemandViewController class] withInfo:@"" withTitle:@"我的供求" withOther:nil];
        //        });
    }else if([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"projectpush"]){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
        [curNav popToRootViewControllerAnimated:NO];
        BaseViewController *baseV=curNav.viewControllers.firstObject;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [baseV pushController:[UserProjectViewController class] withInfo:@"" withTitle:@"我的项目" withOther:nil];
        });
    }else if([[dicPush valueForJSONStrKey:@"type"] isEqualToString:@"noticepush"]){
        [[NSNotificationCenter defaultCenter] postNotificationName:@"myWebView_nil" object:nil userInfo:nil];
        UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
        [curNav popToRootViewControllerAnimated:NO];
        BaseViewController *baseV=curNav.viewControllers.firstObject;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [baseV pushController:[CompanyNoticeViewController class] withInfo:@"" withTitle:@"通知" withOther:nil];
        });
    }
    
    
}
-(void)typeButtonClicked:(UITapGestureRecognizer *)tap{
    NSInteger index=tap.view.tag;
    DLog(@"index:%ld",index)
    NSDictionary *dic=[[[[Utility Share] userTypeData] objectForJSONKey:@"cate"] objectAtIndex:index];
    [self pushController:[V4LicensePlateViewController class] withInfo:@"type" withTitle:[dic valueForJSONStrKey:@"name"] withOther:dic];
}
-(void)sendAddPZClicked{
    UINavigationController *curNav = [[[[Utility Share] CustomTabBar_zk] viewControllers] objectAtIndex:[[[Utility Share] CustomTabBar_zk]selectedIndex]];
    BaseViewController *bview=(BaseViewController *)[curNav.viewControllers objectAtIndex:0];
    [bview pushController:[V4AddLicensePlateViewController class] withInfo:nil withTitle:@"牌照上传"];
}
#pragma mark UIScrollView
- (void) scrollViewDidScroll: (UIScrollView*) scrollview{
    if (scrollTypeBG==scrollview) {
        CGFloat imageW = scrollTypeBG.frame.size.width;
        CGFloat currentOffsetX = scrollTypeBG.contentOffset.x;
        int currentPage = (int) (currentOffsetX+imageW*0.5)/imageW;
        _pageControl.currentPage = currentPage;
    }
    
}

#pragma mark LJImageRollingViewDelegate
-(void)selectView:(LJImageRollingView *)selectView ad:(NSDictionary *)dic index:(NSInteger)index{
    if ([[dic valueForJSONStrKey:@"links"] notEmptyOrNull]) {
        [self pushController:[SelectWebUrlViewController class] withInfo:@"" withTitle:@"" withOther:@{@"url":[dic valueForJSONStrKey:@"links"]}];
    }
}


#pragma mark - tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [table_user.dataArray  count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic=[table_user.dataArray objectAtIndex:indexPath.row];
    HomeTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"HomeTableViewCell" forIndexPath:indexPath];
    [cell setValueForDictionary:dic indexPath:indexPath type:@"home"];
    return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithDictionary:[table_user.dataArray objectAtIndex:indexPath.row]];
    [self pushController:[V4TestLicensePlateContentViewController class] withInfo:@"Insurance" withTitle:@"牌照详情" withOther:dic];
    if ([[dic valueForJSONStrKey:@"isread"] isEqualToString:@"0"]) {
        [dic setValue:@"1" forKey:@"isread"];
        [table_user.dataArray replaceObjectAtIndex:indexPath.row withObject:dic];
        [table_user reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
    }
    
}
#pragma mark pop
-(void)popRefreshData{
    boolRefreshData=YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
